<!DOCTYPE html>
<html>
<head>
    <title>IP子网掩码计算器</title>
    <script>
        function calculateHosts() {
            var ip = document.getElementById("ip").value;
            var subnetMask = document.getElementById("subnet-mask").value;
            // subnetMask CIDR表示法  转化为点表示法，具体过程输出
            var ipParts = ip.split('.');
            var subnetMaskParts = subnetMask.split('.');

            var ipBinary = convertToBinary(ipParts);
            var subnetMaskBinary = convertToBinary(subnetMaskParts);

            var networkBits = getNetworkBits(subnetMaskBinary);
            var hostBits = 32 - networkBits;

            var hosts = Math.pow(2, hostBits) - 2;

            document.getElementById("result").innerHTML = "主机数量: " + hosts;

            document.getElementById("ip-binary").innerHTML = "IP地址（二进制）: " + ipBinary;
            document.getElementById("subnet-binary").innerHTML = "子网掩码（二进制）: " + subnetMaskBinary;
            document.getElementById("network-bits").innerHTML = "网络位数: " + networkBits;
            document.getElementById("host-bits").innerHTML = "主机位数: " + hostBits;
            document.getElementById("result").innerHTML = "主机数量: " + hosts;
        }

        function convertToBinary(parts) {
            var binary = "";

            for (var i = 0; i < parts.length; i++) {
                var decimal = parseInt(parts[i]);
                var binaryPart = decimal.toString(2).padStart(8, '0');
                binary += binaryPart;
            }

            return binary;
        }

        function getNetworkBits(subnetMaskBinary) {
            var count = 0;

            for (var i = 0; i < subnetMaskBinary.length; i++) {
                if (subnetMaskBinary[i] === '1') {
                    count++;
                } else {
                    break;
                }
            }

            return count;
        }
    </script>
</head>
<body>
    <h1>IP子网掩码计算器</h1>
    <p>IP地址：<input type="text" id="ip" placeholder="请输入IP地址" value="152.178.132.95"></p>
    <p>子网掩码：<input type="text" id="subnet-mask" placeholder="请输入子网掩码" value="24"></p>
    <button onclick="calculateHosts()">计算主机数量</button>
    <p id="result"></p>

    <p id="ip-binary"></p>
    <p id="subnet-binary"></p>
    <p id="network-bits"></p>
    <p id="host-bits"></p>
    <p id="result"></p>
</body>
</html>
